<template>
  <ContentWrap>
    <div :class="searchVisible ? 'flex flex-row flex-wrap mb-2' : 'flex flex-row flex-wrap'">
      <el-button plain type="primary" @click="openForm('create')" v-hasRole="['shop_admin']">
        <Icon class="mr-5px" icon="ep:plus" />
        新增
      </el-button>
      <el-button plain type="success" @click="searchVisible = !searchVisible">
        <Icon class="mr-5px" icon="ep:operation" />
        {{ searchVisible ? '关闭筛选' : '打开筛选' }}
      </el-button>
      <el-text type="info">
        <span class="ml-5px">{{ searchVisible ? '点击关闭筛选条件' : '点击打开筛选条件' }}</span>
      </el-text>
      <div class="flex-1"></div>
      <el-button @click="resetQuery">
        <Icon class="mr-5px" icon="ep:refresh" />
        刷新列表
      </el-button>
    </div>
    <el-form v-if="searchVisible" ref="searchFormRef" :model="tableData.searchParam" inline>
      <el-form-item label="关键词" prop="keyword">
        <el-input
          v-model="tableData.searchParam.keyword"
          class="!w-240px"
          placeholder="请输入菜品名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-select
          v-model="tableData.searchParam.categoryId"
          class="!w-160px"
          placeholder="请选择分类"
          clearable
        >
          <el-option
            v-for="category in categoryList"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="属性" prop="attribute">
        <el-select
          v-model="tableData.searchParam.attribute"
          class="!w-160px"
          placeholder="请选择属性"
          clearable
        >
          <el-option
            v-for="(label, value) in ATTRIBUTE_MAP"
            :key="value"
            :label="label"
            :value="Number(value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="tableData.searchParam.status"
          class="!w-160px"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="(label, value) in STATUS_MAP"
            :key="value"
            :label="label"
            :value="Number(value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="tableData.searchParam.createTime"
          type="datetimerange"
          value-format="YYYY-MM-DD HH:mm:ss"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
  <ContentWrap>
    <div class="mt-[5px]">
      <el-table :data="tableData.list" size="large" v-loading="tableData.loading">
        <template #empty>
          <span>{{ !tableData.loading ? '没有相关数据' : '' }}</span>
        </template>
        <el-table-column label="菜名" min-width="160">
          <template #default="{ row }">
            <div>{{ row.title }}</div>
          </template>
        </el-table-column>
        <el-table-column label="封面" min-width="100">
          <template #default="{ row }">
            <el-image
              class="w-50px h-50px"
              :src="row.coverUrl"
              :preview-src-list="[row.coverUrl]"
              preview-teleported
              hide-on-click-modal
            />
          </template>
        </el-table-column>
        <el-table-column
          v-hasRole="['super_admin', 'platform_admin', 'tenant_admin']"
          label="所属店铺"
          min-width="180"
        >
          <template #default="{ row }">
            <div>{{ row.shop?.name || row.shopId }}</div>
          </template>
        </el-table-column>
        <el-table-column label="分类" min-width="100">
          <template #default="{ row }">
            <div>{{ row.categoryName || '#' + row.categoryId }}</div>
          </template>
        </el-table-column>
        <el-table-column label="属性" min-width="100">
          <template #default="{ row }">
            <div>{{ ATTRIBUTE_MAP[row.attribute] }}</div>
          </template>
        </el-table-column>
        <el-table-column label="计价" min-width="120">
          <template #default="{ row }">
            <div v-if="row.price > 0">
              {{ fenToYuan(row.price) }}元/{{ row.unitValue }}{{ row.unitName }}
            </div>
            <div v-else> 按重量计价/{{ row.unitValue }}{{ row.unitName }} </div>
          </template>
        </el-table-column>
        <el-table-column label="限购" min-width="100">
          <template #default="{ row }">
            <div v-if="row.minQuantity > 0 || row.maxQuantity > 0">
              {{ row.minQuantity }}-{{ row.maxQuantity }}
            </div>
            <div v-else>不限购</div>
          </template>
        </el-table-column>
        <el-table-column label="状态" min-width="100">
          <template #default="{ row }">
            <div>{{ STATUS_MAP[row.status] }}</div>
          </template>
        </el-table-column>
        <el-table-column label="排序" width="90" sortable prop="sort">
          <template #default="{ row }">
            <div>{{ row.sort }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="100" align="center" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="openForm('update', scope.row.id)">
              编辑
            </el-button>
            <el-button
              v-hasRole="['shop_admin']"
              link
              type="danger"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        v-model:limit="tableData.searchParam.pageSize"
        v-model:page="tableData.searchParam.pageNo"
        :total="tableData.total"
        @pagination="loadTableData"
      />
    </div>
  </ContentWrap>

  <ProductForm ref="formRef" @success="loadTableData" />
</template>

<script lang="ts" setup name="ProductList">
import * as ProductApi from '@/api/dine/product/ProductApi'
import * as CategoryApi from '@/api/dine/category/CategoryApi'
import { FormInstance } from 'element-plus'
import { fenToYuan } from '@/utils'
import ProductForm from './ProductForm.vue'
import { ATTRIBUTE_MAP, STATUS_MAP } from '@/views/dine/product/enums'

const { t } = useI18n()
const message = useMessage()

const searchVisible = ref(false)

const tableData = reactive({
  total: 0,
  loading: true,
  list: [],
  searchParam: {
    pageNo: 1,
    pageSize: 10,
    keyword: '',
    categoryId: undefined,
    attribute: undefined,
    status: undefined,
    createTime: []
  }
})

const categoryList = ref<any[]>([])

const loadCategoryList = async () => {
  try {
    categoryList.value = await CategoryApi.getList()
  } catch (err) {
    console.error('获取分类列表失败', err)
  }
}

const loadTableData = () => {
  tableData.loading = true
  ProductApi.getPage({
    ...tableData.searchParam
  })
    .then((res: any) => {
      tableData.loading = false
      tableData.list = res.list
      tableData.total = res.total
    })
    .catch(() => {
      tableData.loading = false
    })
}

const searchFormRef = ref<FormInstance>()

const handleQuery = () => {
  tableData.searchParam.pageNo = 1
  loadTableData()
}

const resetQuery = () => {
  searchFormRef.value?.resetFields()
  handleQuery()
}

const formRef = ref()
const openForm = (type: string, id?: number | string) => {
  formRef.value.open(type, id)
}

const handleDelete = async (id: number | string) => {
  try {
    await message.delConfirm()
    await ProductApi.deleteById(id)
    message.success(t('common.delSuccess'))
    loadTableData()
  } catch {}
}

onMounted(() => {
  handleQuery()
  loadCategoryList()
})
</script>
